#include <iostream>
#include <cstdio>
#include <string>
#include <ctime>
#include <mutex>
#include <cstdlib>
#include <unistd.h>
#include <pthread.h>
using namespace std;

class tickets
{
private:
    int ticket;
    pthread_mutex_t mx;

public:
    tickets()
        : ticket(1000)
    {
        //初始化互斥锁
        pthread_mutex_init(&mx, nullptr);
    }
    ~tickets()
    {
        //销毁互斥锁
        pthread_mutex_destroy(&mx);
    }
    bool buy_tickets()
    {
        bool ret = true;
        //加锁
        pthread_mutex_lock(&mx);
        if (ticket > 0)
        {
            usleep(1000);
            cout << "我是[" << pthread_self() << "]线程，我正在抢第" << ticket << "张票" << endl;
            ticket--;
            printf("");
        }
        else
        {
            cout << "票已经卖完了" << endl;
            ret = false;
        }
        //解锁
        pthread_mutex_unlock(&mx);
        return ret;
    }
};
void *pthread_run(void *args)
{
    tickets *t = (tickets *)args;
    while (true)
    {
        if (!t->buy_tickets())
            break;
    }
}
int main()
{
    tickets *t = new tickets();
    pthread_t tid[5];
    for (int i = 0; i < 5; i++)
    {
        pthread_create(tid + i, nullptr, pthread_run, (void *)t);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_join(tid[i], nullptr);
    }
    return 0;
}